﻿using IPC.Communication;
using IPC.Communication.Core.Types;
using IPC.Communication.Profinet.AllenBradley;
using IPC.Communication.Profinet.Siemens;
//using IPC.DbMapper;
using IPC.ListConnect.ListProprety;
using IPC.ListConnect.Profinet;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IPC.LogCommon.DelegateAndEvent;

namespace IPC.ListConnect.Connect
{
    public class SiemensConnect : BaseConnect
    {
        #region 字段
        private SiemensClient _siemensClient;
        #endregion

        #region 构造函数
        public SiemensConnect(string connectName,string ip,int port,int slot,int rack,SiemensVersion siemensVersion):base(connectName, ip, port, slot, rack, siemensVersion) 
        {
            _siemensClient = new SiemensClient(siemensVersion, ip, port, Convert.ToByte(slot), Convert.ToByte(rack));
            OperateResult operateResult = _siemensClient.Open();
            if (operateResult.IsSuccess)
            {
                IsOpen = true;
                DelegateAndEvent.Instance.AddAlarmInfo($"{connectName} 连接成功");
            }
            else
            {
                IsOpen = false;
                DelegateAndEvent.Instance.AddAlarmInfo($"{connectName} 连接失败 {operateResult.Message}");
            }
        }
        #endregion

        #region 读

        /// <summary>
        /// 按组读 返回json
        /// </summary>
        /// <param name="equipChannel"></param>
        /// <param name="equip"></param>
        /// <param name="group"></param>
        public override string ReadJson(string channelName, string equip, string groupName = "")
        {
            base.Read(equip, groupName);
            _readTags.Clear();
            _listTags.Clear();
            string equipFullName = GetEquipFullName(channelName, equip);
            string groupFullName = GetGroupFullName(channelName, equip, groupName);
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到标签";
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = false;
            readResult.Message = "未找到标签";

            foreach (var item in EquipChannels.Instance.EquipChannelList)
            {
                if (item.ChannelName == channelName)
                {
                    if (!item.Equips.ContainsKey(equipFullName))
                    {
                        operateResult.IsSuccess = false;
                        operateResult.Message = $"未找到{equipFullName}设备";
                        readResult.IsSuccess = operateResult.IsSuccess;
                        readResult.Message = operateResult.Message;
                        return JsonConvert.SerializeObject(readResult);
                    }

                    if (!JudgeHaveEquipOrGroup(item, equipFullName, groupName, out operateResult))
                    {
                        readResult.IsSuccess = operateResult.IsSuccess;
                        readResult.Message = operateResult.Message;
                        return JsonConvert.SerializeObject(readResult);
                    }


                    if (groupName == "")
                    {
                        foreach (var itemTag in item.Equips[equipFullName].Tags.Values)
                        {
                            switch (itemTag.ReadWrite)
                            {
                                case ReadWrite.Read:
                                    _listTags.Add(itemTag);
                                    break;
                                case ReadWrite.ReadWrite:
                                    _listTags.Add(itemTag);
                                    break;
                                case ReadWrite.Write:
                                    _listTags.Add(itemTag);
                                    break;
                            }
                        }
                    }
                    else
                    {
                        foreach (var itemTag in item.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                        {
                            switch (itemTag.ReadWrite)
                            {
                                case ReadWrite.Read:
                                    _listTags.Add(itemTag);
                                    break;
                                case ReadWrite.ReadWrite:
                                    _listTags.Add(itemTag);
                                    break;
                                case ReadWrite.Write:
                                    _listTags.Add(itemTag);
                                    break;
                            }
                        }
                    }
                    break;
                }
            }

            foreach (var item in _listTags)
            {
                readResult.IsSuccess = item.IsSuccess;
                readResult.Message = item.Result;
                readResult.Result.Add(item.Name, item.Value);
            }
            _listTags.Clear();
            return JsonConvert.SerializeObject(readResult);
        }

        /// <summary>
        /// 单点读 返回json
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="equipName"></param>
        /// <param name="tagName"></param>
        /// <param name="groupName"></param>
        public override string ReadJson(string channelName, string equipName, string tagName, string groupName = "")
        {
            base.Read(channelName, equipName, tagName, groupName);
            _readTags.Clear();
            _listTags.Clear();
            string equipFullName = GetEquipFullName(channelName, equipName);
            string groupFullName = GetGroupFullName(channelName, equipName, groupName);
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到标签";
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = false;
            readResult.Message = "未找到标签";

            foreach (var itemChannel in EquipChannels.Instance.EquipChannelList)
            {
                if (channelName == itemChannel.ChannelName)
                {
                    if (!JudgeHaveEquipOrGroup(itemChannel, equipFullName, groupName, out operateResult))
                    {
                        readResult.IsSuccess = operateResult.IsSuccess;
                        readResult.Message = operateResult.Message;
                        return JsonConvert.SerializeObject(readResult);
                    }
                    if (groupName == "")
                    {
                        foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                        {
                            if (itemTag.Name == tagName)
                            {
                                switch (itemTag.ReadWrite)
                                {
                                    case ReadWrite.Read:
                                        _listTags.Add(itemTag);
                                        break;
                                    case ReadWrite.ReadWrite:
                                        _listTags.Add(itemTag);
                                        break;
                                    case ReadWrite.Write:
                                        _listTags.Add(itemTag);
                                        break;
                                }
                                break;
                            }
                        }
                        break;
                    }
                    else
                    {
                        foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                        {
                            if (itemTag.Name == tagName)
                            {
                                switch (itemTag.ReadWrite)
                                {
                                    case ReadWrite.Read:
                                        _listTags.Add(itemTag);
                                        break;
                                    case ReadWrite.ReadWrite:
                                        _listTags.Add(itemTag);
                                        break;
                                    case ReadWrite.Write:
                                        _listTags.Add(itemTag);
                                        break;
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }

            foreach (var item in _listTags)
            {
                readResult.IsSuccess = item.IsSuccess;
                readResult.Message = item.Result;
                readResult.Result.Add(item.Name, item.Value);
            }

            _listTags.Clear();
            return JsonConvert.SerializeObject(readResult);
        }
        #endregion

        #region 写
        /// <summary>
        /// 单点写
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="equipName"></param>
        /// <param name="tagName"></param>
        /// <param name="values"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public override OperateResult Write(string channelName, string equipName, string tagName, string values, string groupName = "")
        {
            base.Write(channelName, equipName, tagName, values, groupName);
            _writeTags.Clear();
            _listTags.Clear();
            string equipFullName = GetEquipFullName(channelName, equipName);
            string groupFullName = GetGroupFullName(channelName, equipName, groupName);
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到点";
            if (!ReConnect())
            {
                operateResult.IsSuccess = false;
                operateResult.Message = "设备连接失败";
                return operateResult;
            }
            try
            {
                foreach (var itemChannel in EquipChannels.Instance.EquipChannelList)
                {
                    if (itemChannel.ChannelName == channelName)
                    {
                        if (!JudgeHaveEquipOrGroup(itemChannel, equipFullName, groupName, out operateResult))
                        {
                            return operateResult;
                        }
                        if (groupName == "")
                        {
                            foreach (var item in itemChannel.Equips[equipFullName].Tags.Values)
                            {
                                if (item.Name == tagName)
                                {
                                    switch (item.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message = "不允许写";
                                            return operateResult;
                                        default:
                                            ////
                                            operateResult.Message = AddWriteTags(item.Address, item.DataType, values);
                                            break;
                                    }
                                }
                            }
                            break;
                        }
                        else
                        {
                            foreach (var item in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                            {
                                if (item.Name == tagName)
                                {
                                    switch (item.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message = "不允许写";
                                            return operateResult;
                                        default:
                                            ////
                                            operateResult.Message = AddWriteTags(item.Address, item.DataType, values);
                                            break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                ReadResult readResult = Write(_writeTags);
                operateResult.IsSuccess = readResult.IsSuccess;
                operateResult.Message = readResult.Message;
                if (!readResult.IsSuccess)
                {
                    IsOpen = false;
                }
            }
            catch (Exception ex)
            {
                operateResult.IsSuccess = false;
                operateResult.Message = ex.Message;
                IsOpen = false;
            }
            _listTags.Clear();
            return operateResult;
        }

        /// <summary>
        /// 按组写
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="equipName"></param>
        /// <param name="values"></param>
        /// <param name="startTag"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public override OperateResult Write(string channelName, string equipName, string[] values, string startTag = "", string groupName = "")
        {
            base.Write(channelName, equipName, values, startTag, groupName);
            _writeTags.Clear();
            _listTags.Clear();
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到点";
            string equipFullName = GetEquipFullName(channelName, equipName);
            string groupFullName = GetGroupFullName(channelName, equipName, groupName);

            if (!ReConnect())
            {
                operateResult.IsSuccess = false;
                operateResult.Message = "设备连接失败";
                return operateResult;
            }

            try
            {
                foreach (var itemChannel in EquipChannels.Instance.EquipChannelList)
                {
                    if (itemChannel.ChannelName == channelName)
                    {
                        if (!JudgeHaveEquipOrGroup(itemChannel, equipFullName, groupName, out operateResult))
                        {
                            return operateResult;
                        }
                        if (groupName == "")
                        {
                            if (startTag != "")
                            {
                                bool writeFlag = false;
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                                {
                                    if (itemTag.Name == startTag)
                                    {
                                        writeFlag = true;
                                    }
                                    if (writeFlag)
                                    {
                                        if (!ArrayEnough(values, j))
                                        {
                                            break;
                                        }
                                        operateResult.IsSuccess = true;
                                        switch (itemTag.ReadWrite)
                                        {
                                            case ReadWrite.Read:
                                                operateResult.IsSuccess = false;
                                                operateResult.Message += $"{itemTag.FullName} 不允许写";
                                                break;
                                            default:
                                                operateResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                                break;
                                        }
                                        j++;
                                    }
                                }
                            }
                            else
                            {
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                                {
                                    if (!ArrayEnough(values, j))
                                    {
                                        break;
                                    }
                                    operateResult.IsSuccess = true;
                                    switch (itemTag.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message += $"{itemTag.FullName} 不允许写";
                                            break;
                                        default:
                                            operateResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                            break;
                                    }
                                    j++;
                                }
                            }
                        }
                        else
                        {
                            if (startTag != "")
                            {
                                bool writeFlag = false;
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                                {
                                    if (itemTag.Name == startTag)
                                    {
                                        writeFlag = true;
                                    }
                                    if (writeFlag)
                                    {
                                        if (!ArrayEnough(values, j))
                                        {
                                            break;
                                        }
                                        operateResult.IsSuccess = true;
                                        switch (itemTag.ReadWrite)
                                        {
                                            case ReadWrite.Read:
                                                operateResult.IsSuccess = false;
                                                operateResult.Message += $"{itemTag.FullName} 不允许写";
                                                break;
                                            default:
                                                operateResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                                break;
                                        }
                                        j++;
                                    }
                                }
                            }
                            else
                            {
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                                {
                                    if (!ArrayEnough(values, j))
                                    {
                                        break;
                                    }
                                    operateResult.IsSuccess = true;
                                    switch (itemTag.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message += $"{itemTag.FullName} 不允许写";
                                            break;
                                        default:
                                            operateResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                            break;
                                    }
                                    j++;
                                }
                            }
                        }
                        break;
                    }
                }

                ReadResult readResult = Write(_writeTags);
                operateResult.IsSuccess = readResult.IsSuccess;
                operateResult.Message = readResult.Message;
                if (!readResult.IsSuccess)
                {
                    IsOpen = false;
                }
                return operateResult;
            }
            catch (Exception ex)
            {
                operateResult.IsSuccess = false;
                operateResult.Message = ex.Message;
                IsOpen = false;
            }
            _listTags.Clear();
            return operateResult;
        }

        /// <summary>
        /// 按组写
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="equipName"></param>
        /// <param name="values"></param>
        /// <param name="startTag"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public override string WriteJson(string channelName, string equipName, string[] values, string startTag = "", string groupName = "")
        {
            base.Write(channelName, equipName, values, startTag, groupName);
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到点";
            string equipFullName = GetEquipFullName(channelName, equipName);
            string groupFullName = GetGroupFullName(channelName, equipName, groupName);
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = false;
            readResult.Message = "未找到标签";

            if (!ReConnect())
            {
                readResult.IsSuccess = false;
                readResult.Message = "设备连接失败";
                return JsonConvert.SerializeObject(readResult);
            }

            try
            {
                foreach (var itemChannel in EquipChannels.Instance.EquipChannelList)
                {
                    if (itemChannel.ChannelName == channelName)
                    {
                        if (!JudgeHaveEquipOrGroup(itemChannel, equipFullName, groupName, out operateResult))
                        {
                            readResult.IsSuccess = operateResult.IsSuccess;
                            readResult.Message = operateResult.Message;
                            return JsonConvert.SerializeObject(readResult);
                        }
                        if (groupName == "")
                        {
                            if (startTag != "")
                            {
                                bool writeFlag = false;
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                                {
                                    if (itemTag.Name == startTag)
                                    {
                                        writeFlag = true;
                                    }
                                    if (writeFlag)
                                    {
                                        if (!ArrayEnough(values, j))
                                        {
                                            break;
                                        }
                                        operateResult.IsSuccess = true;
                                        switch (itemTag.ReadWrite)
                                        {
                                            case ReadWrite.Read:
                                                operateResult.IsSuccess = false;
                                                operateResult.Message += $"{itemTag.FullName} 不允许写";
                                                readResult.IsSuccess = operateResult.IsSuccess;
                                                readResult.Message = operateResult.Message;
                                                break;
                                            default:
                                                itemTag.Value = values[j];
                                                break;
                                        }
                                        j++;
                                    }
                                }
                            }
                            else
                            {
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                                {
                                    if (!ArrayEnough(values, j))
                                    {
                                        break;
                                    }
                                    operateResult.IsSuccess = true;
                                    switch (itemTag.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message += $"{itemTag.FullName} 不允许写";
                                            readResult.IsSuccess = operateResult.IsSuccess;
                                            readResult.Message = operateResult.Message;
                                            break;
                                        default:
                                            itemTag.Value = values[j];
                                            break;
                                    }
                                    j++;
                                }
                            }
                        }
                        else
                        {
                            if (startTag != "")
                            {
                                bool writeFlag = false;
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                                {
                                    if (itemTag.Name == startTag)
                                    {
                                        writeFlag = true;
                                    }
                                    if (writeFlag)
                                    {
                                        if (!ArrayEnough(values, j))
                                        {
                                            break;
                                        }
                                        operateResult.IsSuccess = true;
                                        switch (itemTag.ReadWrite)
                                        {
                                            case ReadWrite.Read:
                                                operateResult.IsSuccess = false;
                                                operateResult.Message += $"{itemTag.FullName} 不允许写";
                                                readResult.IsSuccess = operateResult.IsSuccess;
                                                readResult.Message = operateResult.Message;
                                                break;
                                            default:
                                                itemTag.Value = values[j];
                                                break;
                                        }
                                        j++;
                                    }
                                }
                            }
                            else
                            {
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                                {
                                    if (!ArrayEnough(values, j))
                                    {
                                        break;
                                    }
                                    operateResult.IsSuccess = true;
                                    switch (itemTag.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message += $"{itemTag.FullName} 不允许写";
                                            readResult.IsSuccess = operateResult.IsSuccess;
                                            readResult.Message = operateResult.Message;
                                            break;
                                        default:
                                            itemTag.Value = values[j];
                                            break;
                                    }
                                    j++;
                                }
                            }
                        }
                        break;
                    }
                }
                return JsonConvert.SerializeObject(readResult);
            }
            catch (Exception ex)
            {
                operateResult.IsSuccess = false;
                operateResult.Message = ex.Message;
                readResult.IsSuccess = operateResult.IsSuccess;
                readResult.Message = operateResult.Message;
            }
            return JsonConvert.SerializeObject(readResult);
        }

        /// <summary>
        /// 单点写
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="equipName"></param>
        /// <param name="tagName"></param>
        /// <param name="values"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public override string WriteJson(string channelName, string equipName, string tagName, string values, string groupName = "")
        {
            base.WriteJson(channelName, equipName, tagName, values, groupName);
            _writeTags.Clear();
            _listTags.Clear();
            string equipFullName = GetEquipFullName(channelName, equipName);
            string groupFullName = GetGroupFullName(channelName, equipName, groupName);
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到点";
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = false;
            readResult.Message = "未找到标签";

            if (!ReConnect())
            {
                readResult.IsSuccess = false;
                readResult.Message = "设备连接失败";
                return JsonConvert.SerializeObject(readResult);
            }

            try
            {
                foreach (var itemChannel in EquipChannels.Instance.EquipChannelList)
                {
                    if (itemChannel.ChannelName == channelName)
                    {
                        if (!JudgeHaveEquipOrGroup(itemChannel, equipFullName, groupName, out operateResult))
                        {
                            readResult.IsSuccess = operateResult.IsSuccess;
                            readResult.Message = operateResult.Message;
                            return JsonConvert.SerializeObject(readResult);
                        }
                        if (groupName == "")
                        {
                            foreach (var item in itemChannel.Equips[equipFullName].Tags.Values)
                            {
                                if (item.Name == tagName)
                                {
                                    switch (item.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message = "不允许写";
                                            readResult.IsSuccess = operateResult.IsSuccess;
                                            readResult.Message = operateResult.Message;
                                            return JsonConvert.SerializeObject(readResult);
                                        default:
                                            readResult.Message = AddWriteTags(item.Address, item.DataType, values);
                                            break;
                                    }
                                }
                            }
                            break;
                        }
                        else
                        {
                            foreach (var item in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                            {
                                if (item.Name == tagName)
                                {
                                    switch (item.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message = "不允许写";
                                            readResult.IsSuccess = operateResult.IsSuccess;
                                            readResult.Message = operateResult.Message;
                                            return JsonConvert.SerializeObject(readResult);
                                        default:
                                            readResult.Message = AddWriteTags(item.Address, item.DataType, values);
                                            break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
                readResult = Write(_writeTags);
                operateResult.IsSuccess = readResult.IsSuccess;
                operateResult.Message = readResult.Message;
                if (!readResult.IsSuccess)
                {
                    IsOpen = false;
                }
            }
            catch (Exception ex)
            {
                operateResult.IsSuccess = false;
                operateResult.Message = ex.Message;
                readResult.IsSuccess = operateResult.IsSuccess;
                readResult.Message = operateResult.Message;
                IsOpen = false;
            }
            _listTags.Clear();
            return JsonConvert.SerializeObject(readResult);
        }

        /// <summary>
        /// 按组写
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="equipName"></param>
        /// <param name="json">json格式的值 格式为["test1","test2"]</param>
        /// <param name="startTag"></param>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public override string WriteByJson(string channelName, string equipName, string json, string startTag = "", string groupName = "")
        {
            base.WriteByJson(channelName, equipName, json, startTag, groupName);
            _writeTags.Clear();
            _listTags.Clear();
            OperateResult operateResult = new OperateResult();
            operateResult.IsSuccess = false;
            operateResult.Message = "未找到点";
            string equipFullName = GetEquipFullName(channelName, equipName);
            string groupFullName = GetGroupFullName(channelName, equipName, groupName);
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = false;
            readResult.Message = "未找到标签";

            if (!ReConnect())
            {
                readResult.IsSuccess = false;
                readResult.Message = "设备连接失败";
                return JsonConvert.SerializeObject(readResult);
            }

            List<string> list = new List<string>();
            try
            {
                list = (List<string>)JsonConvert.DeserializeObject(json, typeof(List<string>));
            }
            catch (Exception ex)
            {
                readResult.IsSuccess = false;
                readResult.Message = "数据转换失败。请检查json格式是否为:[\"test1\",\"test2\"]";
                return JsonConvert.SerializeObject(readResult);
            }
            string[] values = new string[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                values[i] = list[i];
            }
            try
            {
                foreach (var itemChannel in EquipChannels.Instance.EquipChannelList)
                {
                    if (itemChannel.ChannelName == channelName)
                    {
                        if (!JudgeHaveEquipOrGroup(itemChannel, equipFullName, groupName, out operateResult))
                        {
                            readResult.IsSuccess = operateResult.IsSuccess;
                            readResult.Message = operateResult.Message;
                            return JsonConvert.SerializeObject(readResult);
                        }
                        if (groupName == "")
                        {
                            if (startTag != "")
                            {
                                bool writeFlag = false;
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                                {
                                    if (itemTag.Name == startTag)
                                    {
                                        writeFlag = true;
                                    }
                                    if (writeFlag)
                                    {
                                        if (!ArrayEnough(values, j))
                                        {
                                            break;
                                        }
                                        operateResult.IsSuccess = true;
                                        switch (itemTag.ReadWrite)
                                        {
                                            case ReadWrite.Read:
                                                operateResult.IsSuccess = false;
                                                operateResult.Message += $"{itemTag.FullName} 不允许写";
                                                readResult.IsSuccess = operateResult.IsSuccess;
                                                readResult.Message = operateResult.Message;
                                                break;
                                            default:
                                                readResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                                break;
                                        }
                                        j++;
                                    }
                                }
                            }
                            else
                            {
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Tags.Values)
                                {
                                    if (!ArrayEnough(values, j))
                                    {
                                        break;
                                    }
                                    operateResult.IsSuccess = true;
                                    switch (itemTag.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message += $"{itemTag.FullName} 不允许写";
                                            readResult.IsSuccess = operateResult.IsSuccess;
                                            readResult.Message = operateResult.Message;
                                            break;
                                        default:
                                            readResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                            break;
                                    }
                                    j++;
                                }
                            }
                        }
                        else
                        {
                            if (startTag != "")
                            {
                                bool writeFlag = false;
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                                {
                                    if (itemTag.Name == startTag)
                                    {
                                        writeFlag = true;
                                    }
                                    if (writeFlag)
                                    {
                                        if (!ArrayEnough(values, j))
                                        {
                                            break;
                                        }
                                        operateResult.IsSuccess = true;
                                        switch (itemTag.ReadWrite)
                                        {
                                            case ReadWrite.Read:
                                                operateResult.IsSuccess = false;
                                                operateResult.Message += $"{itemTag.FullName} 不允许写";
                                                readResult.IsSuccess = operateResult.IsSuccess;
                                                readResult.Message = operateResult.Message;
                                                break;
                                            default:
                                                readResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                                break;
                                        }
                                        j++;
                                    }
                                }
                            }
                            else
                            {
                                int j = 0;
                                foreach (var itemTag in itemChannel.Equips[equipFullName].Groups[groupFullName].Tags.Values)
                                {
                                    if (!ArrayEnough(values, j))
                                    {
                                        break;
                                    }
                                    operateResult.IsSuccess = true;
                                    switch (itemTag.ReadWrite)
                                    {
                                        case ReadWrite.Read:
                                            operateResult.IsSuccess = false;
                                            operateResult.Message += $"{itemTag.FullName} 不允许写";
                                            readResult.IsSuccess = operateResult.IsSuccess;
                                            readResult.Message = operateResult.Message;
                                            break;
                                        default:
                                            readResult.Message = AddWriteTags(itemTag.Address, itemTag.DataType, values[j]);
                                            break;
                                    }
                                    j++;
                                }
                            }
                        }
                        break;
                    }
                }

                readResult = Write(_writeTags);
                operateResult.IsSuccess = readResult.IsSuccess;
                operateResult.Message = readResult.Message;
                if (!readResult.IsSuccess)
                {
                    IsOpen = false;
                }

                return JsonConvert.SerializeObject(readResult);
            }
            catch (Exception ex)
            {
                operateResult.IsSuccess = false;
                operateResult.Message = ex.Message;
                readResult.IsSuccess = operateResult.IsSuccess;
                readResult.Message = operateResult.Message;
                IsOpen = false;
            }
            _listTags.Clear();
            return JsonConvert.SerializeObject(readResult);
        }
        #endregion

        #region 判断数组是否够长
        public bool ArrayEnough(string[] strings, int length)
        {
            if (strings.Length > length)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 判断有无设备或组
        /// <summary>
        /// 判断有无设备或组
        /// </summary>
        /// <param name="equipChannel"></param>
        /// <param name="equipFullName"></param>
        /// <param name="groupName"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public bool JudgeHaveEquipOrGroup(EquipChannel equipChannel, string equipFullName, string groupName, out OperateResult operateResult)
        {
            operateResult = new OperateResult();
            operateResult.IsSuccess = true;
            operateResult.Message = "存在";
            bool b1 = false;
            Profinet.Equip equip = null;
            foreach (var item in equipChannel.Equips.Values)
            {
                if (item.EquipFullName == equipFullName)
                {
                    b1 = true;
                    equip = item;
                    break;
                }
            }
            if (!b1)
            {
                operateResult.IsSuccess = false;
                operateResult.Message = $"未找到 {equipFullName} 设备";
                return false;
            }
            if (groupName != "")
            {
                bool b2 = false;
                foreach (var item in equip.Groups.Values)
                {
                    if (item.Name == groupName)
                    {
                        b2 = true;
                        break;
                    }
                }
                if (!b2)
                {
                    operateResult.IsSuccess = false;
                    operateResult.Message = $"未找到 {groupName} 组";
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region 添加读写组

        private Dictionary<string, DataTypeEnum> _readTags = new Dictionary<string, DataTypeEnum>();

        private List<Tag> _writeTags = new List<Tag>();
        private string AddWriteTags(string address,DataType dataType,string value)
        {
            bool success;
            string result = "ok";
            Tag tag = new Tag();
            tag.Address = address;
            tag.DataType = dataType;
            tag.Value = value;
            //bool b;
            switch (dataType)
            {
                case DataType.Bool:
                    (bool b,success) = value.ToBool();
                    if (success)
                    {
                        _writeTags.Add(tag);
                    }
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.Int16:
                    (short s, success) = value.ToShort();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.UInt16:
                    (ushort us, success) = value.ToUShort();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.Int32:
                    (int i, success) = value.ToInt();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.UInt32:
                    (uint ui, success) = value.ToUInt();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.Int64:
                    (long l, success) = value.ToInt64();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.UInt64:
                    (ulong ul, success) = value.ToUInt64();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.Float:
                    (float f, success) = value.ToFloat();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.Double:
                    (double d, success) = value.ToDouble();
                    if (success)
                        _writeTags.Add(tag);
                    else
                    {
                        result = address + "数据类型错误";
                    }
                    break;
                case DataType.String:
                    _writeTags.Add(tag);
                    break;
                default:
                    result = "数据类型不支持";
                    break;
            }
            if (result != "ok")
            {
                DelegateAndEvent.Instance.AddAlarmInfo(result);
            }
            return result;
            //_writeTags.Add(address,value);
        }

        private List<Profinet.Tag> _listTags = new List<Profinet.Tag>();
        #endregion

        #region 断开重连
        private bool ReConnect()
        {
            if (!IsOpen)
            {
                _siemensClient.Close();
                OperateResult operateResult = _siemensClient.Open();
                return operateResult.IsSuccess;
            }
            return true;
        }
        #endregion

        #region 处理string类型长度
        private ushort GetStringTypeLength(string name)
        {
            ushort length = 0;
            string[] strings = name.Split('.');
            if (strings.Length <= 2)
                return 0;
            (length, bool b) = strings[2].ToUShort();
            return length;
        }
        #endregion

        #region 处理string类型地址
        private string GetStringTypeAddress(string address)
        {
            ushort length = 0;
            string[] strings = address.Split('.');
            if (strings.Length <= 2)
                return address;
            string s = string.Empty;
            for(int i=0;i< strings.Length-1; i++)
            {
                s += strings[i] + ".";
            }
            if(s.EndsWith(".")) s = s.Substring(0,s.Length-1);
            return s;
        }
        #endregion

        #region 写处理
        private ReadResult Write(List<Tag> tags)
        {
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = true;
            OperateResult operateResult = new OperateResult();
            foreach (Tag tag in tags)
            {
                switch (tag.DataType)
                {
                    case DataType.Bool:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToBool().Item1);
                        break;
                    case DataType.Byte:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToByte().Item1); break;
                    case DataType.UInt16:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToUShort().Item1); break;
                    case DataType.Int16:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToUShort().Item1); break;
                    case DataType.UInt32:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToUInt().Item1); break;
                    case DataType.Int32:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToInt().Item1); break;
                    case DataType.UInt64:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToUInt64().Item1); break;
                    case DataType.Int64:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToInt64().Item1); break;
                    case DataType.Float:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToFloat().Item1); break;
                    case DataType.Double:
                        operateResult = _siemensClient.Write(tag.Address, tag.Value.ToDouble().Item1); break;
                    case DataType.String:
                        
                        operateResult = _siemensClient.Write(tag.Address, tag.Value); break;
                    default:
                        operateResult.IsSuccess = false;
                        operateResult.Message = "数据类型不支持";
                        break;
                }

                if (!operateResult.IsSuccess)
                {
                    readResult.IsSuccess = false;
                    readResult.Message = operateResult.Message;
                    DelegateAndEvent.Instance.AddAlarmInfo($"写入失败{readResult.Message}");
                    return readResult;
                }
            }
            readResult.IsSuccess = operateResult.IsSuccess;
            readResult.Message = operateResult.Message;
            return readResult;
        }
        #endregion

        #region 读处理
        /// <summary>
        /// 读
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        private ReadResult Read(Tag tag)
        {
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = true;
            readResult.Message = "";
            object value = null;
            if (tag.ReadWrite == ReadWrite.Write)
            {
                readResult.IsSuccess = false;
                readResult.Message = "";
                tag.RealValue = "不允许读";
                tag.IsSuccess = false;
                tag.Result = "不允许读";
                readResult.Result.Add(tag.Name, "不允许读");
                return readResult;
            }
            switch (tag.DataType)
            {
                case DataType.UInt64:
                    OperateResult<ulong> operateResult = _siemensClient.ReadUInt64(tag.Address);
                    if (operateResult.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResult.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResult.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResult.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResult.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Float:
                    OperateResult<float> operateResultFloat = _siemensClient.ReadFloat(tag.Address);
                    if (operateResultFloat.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultFloat.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultFloat.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultFloat.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultFloat.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Double:
                    OperateResult<double> operateResultDouble = _siemensClient.ReadDouble(tag.Address);
                    if (operateResultDouble.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultDouble.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultDouble.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultDouble.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultDouble.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Bool:
                    OperateResult<bool> operateResultBool = _siemensClient.ReadBool(tag.Address);
                    if (operateResultBool.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = operateResultBool.Content.ToString();
                        readResult.Result.Add(tag.Name, operateResultBool.Content.ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultBool.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultBool.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.String:
                    OperateResult<string> operateResultString = _siemensClient.ReadString(tag.Address);
                    if (operateResultString.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = operateResultString.Content.ToString();
                        readResult.Result.Add(tag.Name, operateResultString.Content);
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultString.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultString.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Byte:
                    OperateResult<byte[]> operateResultByte = _siemensClient.Read(tag.Address,1);
                    if (operateResultByte.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = operateResultByte.Content[0].ToString();
                        readResult.Result.Add(tag.Name, operateResultByte.Content[0].ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultByte.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultByte.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Int16:
                    OperateResult<short> operateResultShort = _siemensClient.ReadInt16(tag.Address);
                    if (operateResultShort.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultShort.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultShort.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultShort.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultShort.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.UInt16:
                    OperateResult<ushort> operateResultUShort = _siemensClient.ReadUInt16(tag.Address);
                    if (operateResultUShort.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultUShort.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultUShort.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultUShort.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultUShort.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Int32:
                    OperateResult<int> operateResultInt = _siemensClient.ReadInt32(tag.Address);
                    if (operateResultInt.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultInt.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultInt.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultInt.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultInt.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.UInt32:
                    OperateResult<uint> operateResultUInt = _siemensClient.ReadUInt32(tag.Address);
                    if (operateResultUInt.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultUInt.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultUInt.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultUInt.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultUInt.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                case DataType.Int64:
                    OperateResult<long> operateResultLong = _siemensClient.ReadInt64(tag.Address);
                    if (operateResultLong.IsSuccess)
                    {
                        tag.IsSuccess = true;
                        tag.Result = "成功";
                        tag.RealValue = (operateResultLong.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString();
                        readResult.Result.Add(tag.Name, (operateResultLong.Content.ToString().ToDouble().Item1 / tag.Zoom).ToString());
                    }
                    else
                    {
                        tag.IsSuccess = false;
                        tag.Result = operateResultLong.Message;
                        readResult.IsSuccess = false;
                        readResult.Message = operateResultLong.Message;
                        IsOpen = false;
                        tag.RealValue = "未知";
                        readResult.Result.Add(tag.Name, "未知");
                    }
                    break;
                default:
                    tag.IsSuccess = false;
                    tag.Result = "数据类型不支持";
                    readResult.IsSuccess = false;
                    readResult.Message = "数据类型不支持";
                    tag.RealValue = "数据类型不支持";
                    readResult.Result.Add(tag.Name, "数据类型不支持");
                    break;
            }
            return readResult;
        }


        private ReadResult ReadValue(Tag tag)
        {
            ReadResult readResult = new ReadResult();
            readResult.IsSuccess = tag.IsSuccess;
            readResult.Message = tag.Result;
            readResult.Result.Add(tag.Name,tag.Value);
            return readResult;
        }
        #endregion
    }
}
